<?php

namespace app\api\server;

use app\api\server\Order as ServerOrder;
use app\common\controller\Api;
use app\common\model\CouponLog;
use app\common\model\goods\Category;
use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\order\Goods;
use app\common\model\order\Order;
use app\common\model\order\Refund as OrderRefund;
use think\Controller;
use think\Db;

/**
 * 售后逻辑
 */
class Refund extends Controller
{

    static public function refund_order($param)
    {
        extract($param);
        $model = new OrderRefund();
        if ($type != 'all') {
            $model->where('refund.refund_status', $type);
        }
        if (isset($shop_id) && $shop_id) {
            $model->where('shop_id', $shop_id);
        }
        if (isset($user_id) && $user_id) {
            $model->where('user_id', $user_id);
        }
        return $model->with(['goods'])->order('id desc')->paginate();
    }

    static public function refund_examine($param)
    {
        extract($param);
        $info = OrderRefund::get($id);
        if ($info->refund_status != '10') {
            exception('订单状态错误');
        }
        Db::startTrans();
        try {
            $info->refund_status = $refund_status;
            $info->teketime = time();
            $info->save();
            Goods::update(['refund_status' => $refund_status], ['id' => $info->o_g_id]);
            self::check_after($info->order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }
    static public function cancel_after($param)
    {
        extract($param);
        Db::startTrans();
        try {
            $refund = OrderRefund::get($id);
            if (!$refund) {
                exception('数据不存在');
            }
            if (!in_array($refund->refund_status, ['0', '10'])) {
                exception('已审核或已取消');
            }
            Goods::update(['refund_status' => 0], ['id' => $refund->o_g_id]);
            $refund->delete();
            self::check_after($refund->order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $refund->delete();
    }

    //申请退款
    static public function apply_refund($data)
    {
        extract($data);
        $order = Order::get($order_id);
        if (!isset($order) || !$order) {
            exception('订单不存在');
        }
        $auto_settlement = config('site.auto_settlement');
        $settletime = $order->paytime + $auto_settlement * 86400;
        if (time() > $settletime) {
            exception('支付成功' . $auto_settlement . '天以内可售后');
        }
        if (!in_array($order->order_status, ['10', '20', '30'])) {
            exception('商品无法售后');
        }
        $goods = Goods::get($o_g_id);
        if (!isset($goods) || !$goods) {
            exception('订单商品不存在');
        }
        if (!in_array($goods->refund_status, ['-1', '0'])) {
            exception('订单商品售后已申请');
        }
        if ($order->pay_type == '4') {
            $refund_fee = $goods->pay_point;
        } else {
            $refund_fee = $goods->pay_fee;
        }
        $param = [
            'refund_sn' => sn('order_refund', 'refund_sn', 'RF'),
            'order_id' => $order_id,
            'o_g_id' => $o_g_id,
            'spec_id' => $goods->spec_id,
            'goods_id' => $goods->goods_id,
            'refund_fee' => $refund_fee,
            'refund_type' => $refund_type,
            'refund_reason' => $refund_reason,
            'refund_mark' => $refund_mark,
            'image' => $image,
            'user_id' => $user_id,
            'num' => $goods->goods_num,
        ];
        Db::startTrans();
        try {
            $goods->refund_status = '10';
            $goods->save();
            OrderRefund::create($param, true);
            self::check_after($order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }

    //判断订单是否全部售后
    public static function check_after($order_id)
    {
        $order = Order::get($order_id);
        if (!$order) {
            exception('订单不存在');
        }
        $lists = Goods::all(['order_id' => $order_id]);
        $count = Goods::where('order_id', $order_id)->count();
        $number = $num = 0;
        foreach ($lists as $k => &$v) {
            if ($v->refund_status == '10') {
                $order->refund_status = '10';
                break;
            }
            if ($v->refund_status == '20') {
                $num++;
                unset($lists[$k]);
            }
            if (in_array($v->refund_status, ['0', '-1'])) {
                $number++;
            }
        }
        $goods = Goods::where('order_id', $order_id)->where('refund_status', '<>', '20')->field('sum(goods_num) as total_num ,sum(subtotal) as pay_fee')->find();
        if ($goods) {
            $order->total_num = $goods['total_num'];
            $order->pay_fee = $goods['pay_fee'];
        }
        if ($count == $num) {
            $order->refund_status = '20';
            if ($order->coupon_id > 0) {
                CouponLog::update(['state' => '1'], ['id' => $order->coupon_id]);
            }
        }
        if ($count == $number) {
            $order->refund_status = '0';
        }
        $order->save();
    }
    //填写快递
    static public function add_express($data)
    {
        extract($data);
        $info = OrderRefund::get($id);
        if (!$info) {
            exception('订单不存在');
        }
        return $info->save($data);
    }
}
